<template>
  <el-dialog :title="createGradeForm.id?'修改年级':'新建年级'" :visible.sync="showGradeDialog" width="900px" @open="dialogOpen"
             @closed="handleClose" :destroy-on-close="true" :lock-scroll="false" >
    <el-form :model="createGradeForm" ref="createGradeForm" :rules="editRules" label-width="100px">
      <el-row class="el-row">
        <el-col :span="12">
          <el-form-item label="级别：" prop="school_year">
            <el-select v-model="createGradeForm.school_year" placeholder="请选择级别" class="ele-block" clearable>
              <el-option
                  v-for="item in schoolYears"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="学部：" prop="dept_type">
            <el-select v-model="createGradeForm.dept_type" placeholder="请选择学部" class="ele-block" clearable>
              <el-option
                  v-for="item in deptTypes"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code + ':' + item.name">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row class="el-row">
        <el-col :span="24">
          <el-form-item label="年级名称" prop="name" style="width:100%">
            <el-input v-model="createGradeForm.name" placeholder="请输入年级名称" clearable/>
          </el-form-item>
        </el-col>

      </el-row>

      <div v-for="(item, index) in createGradeForm.dynamicItem" :key="index">
        <el-row class="el-row">
          <el-col :span="8">
            <el-form-item
                label="负责人"
                :prop="'dynamicItem.' + index + '.worker_id'"
                :rules="{required: true, message: '负责人不能为空', trigger: 'blur'}"
                :key="item.key"
            >
              <el-select v-model="item.worker_id" placeholder="请选择负责人" class="ele-block" clearable>
                <el-option
                    v-for="item in workers"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item
                label="职务"
                :prop="'dynamicItem.' + index + '.duty_code'"
                :rules="{required: true, message: '职务不能为空', trigger: 'blur'}"
                :key="item.key"
            >
              <el-select v-model="item.duty_code" placeholder="请选择职务" class="ele-block" clearable>
                <el-option
                    v-for="item in dutys"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code + ':' + item.name">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item>
              <el-button type="danger" icon="el-icon-delete" @click="deleteItem(item, index)" round></el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <el-row class="el-row">
        <el-col :span="6" :offset="20">
          <el-button @click="addItem" type="primary">添加负责人</el-button>
        </el-col>
      </el-row>

      <el-row class="el-row">
        <el-col :span="24">
          <el-form-item label="备注：" prop="note">
            <el-input
                type="textarea"
                :rows="3"
                placeholder="请输入备注"
                v-model="createGradeForm.note">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>
    <div slot="footer">
      <el-button @click="showGradeDialog=false">取消</el-button>
      <el-button type="primary" @click="save">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>

export default {
  name: "CreateGrade",
  data() {
    return {
      schoolYears: [], // 所有级别数据
      deptTypes: [], // 所有学部数据
      workers: [], // 所有教职工
      dutys: [], // 所有教职工职务
      createGradeForm: {
        dynamicItem: [], // 动态表单项
      },  // 表单数据
      editRules: {  // 表单验证规则
        school_year: [
          {required: true, message: '请选择级别', trigger: 'blur'}
        ],
        dept_type: [
          {required: true, message: '请选择学部', trigger: 'blur'}
        ],
      },
      showGradeDialog: this.showCreateGradeForm // 子组件不能直接修改父组件prop参数
    };
  },
  props: {
    showCreateGradeForm: {
      type: Boolean,
      default() {
        return false;
      }
    },
    id: {
      type: Number,
      default() {
        return 0;
      }
    }
  },
  computed: {
  },
  mounted() {

  },
  methods: {
    /**
     * 获取布局详情
     */
    getGradeInfo(){
      this.$http.get('/grade/info?id=' + this.id ).then(res => {
        if (res.data.code === 200) {
          this.createGradeForm = res.data.result;
          this.$set(this.createGradeForm, 'dept_type', this.createGradeForm.dept_type ? this.createGradeForm.dept_type + ':' + this.createGradeForm.dept_name : '');
          this.$set(this.createGradeForm, 'dynamicItem',[]); // TODO 需要完善
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
    },
    /* 保存编辑 */
    save() {
      this.$refs['createGradeForm'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({lock: true});
          this.$http.post('/grade/edit', this.createGradeForm).then(res => {
            loading.close();
            if (res.data.code === 200) {
              this.$message({type: 'success', message: res.data.msg});
              this.$emit('reload')
            } else {
              this.$message.error(res.data.msg);
            }
          }).catch(e => {
            loading.close();
            this.$message.error(e.message);
          });
        } else {
          return false;
        }
      });
      this.showGradeDialog = false;
    },
    addItem () {
      this.createGradeForm.dynamicItem.push({
        worker_id: '',
        duty_code: '',
        key: Date.now()
      })
      // this.$forceUpdate();
    },
    deleteItem (item, index) {
        this.createGradeForm.dynamicItem.splice(index, 1)
    },
    /**
     * 关闭页面
     */
    handleClose(hide) {
      if (hide) {
        hide();
      }
      this.createGradeForm={
        dynamicItem: []
      } // 清空表单数据
      // this.$emit("returnBack");
      this.$emit('update:showCreateGradeForm', false)
    },
    /**
     * 获取级别，即届数
     */
    getSchoolYear() {
      this.$http.get('/grade/getSchoolYear').then(res => {
        this.loading = false;
        if (res.data.code === 200) {
          this.schoolYears = res.data.result;
        } else {
          this.$message.error(res.data.msg || '获取数据失败');
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
    },
    /**
     * 获取学部
     */
    getDeptType() {
      this.$http.get('/grade/getDeptType').then(res => {
        this.loading = false;
        if (res.data.code === 200) {
          this.deptTypes = res.data.result;
        } else {
          this.$message.error(res.data.msg || '获取数据失败');
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
    },
    /**
     * 获取所有教职工
     */
    getWorkers() {
      this.$http.get('/worker/getWorkersIdName').then(res => {
        this.loading = false;
        if (res.data.code === 200) {
          this.workers = res.data.result;
        } else {
          this.$message.error(res.data.msg || '获取数据失败');
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
    },
    /**
     * 获取教职工角色
     */
    getDutys() {
      this.$http.get('/dictType/grade_duty_code').then(res => {
        this.loading = false;
        if (res.data.code === 200) {
          this.dutys = res.data.result;
        } else {
          this.$message.error(res.data.msg || '获取数据失败');
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
    },
    /**
     * 对话框弹出时回调方法
     */
    dialogOpen() {
      this.getSchoolYear();
      this.getDeptType();
      this.getWorkers();
      this.getDutys();
      this.getGradeInfo(); // 获取编辑的年级信息
    }
  },
  watch: {
    showCreateGradeForm(val) { // 监听该值的变化
      this.showGradeDialog = val;
    }
  },

};
</script>

<style scoped>
.el-row {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap
}
</style>
